<template>
  <Head title="优惠券管理" />
  <AdminLayout title="优惠券管理" subtitle="管理商城优惠券和促销活动">
    <template #actions>
      <Link :href="route('admin.coupons.create')" 
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200">
        <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        创建优惠券
      </Link>
    </template>

    <div class="space-y-6">
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5.99C17.52 3 21 6.48 21 11s-3.48 8-8 8H7a2 2 0 01-2-2V5a2 2 0 012-2z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总优惠券数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats?.total_coupons || 0 }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">已发放</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats?.total_distributed || 0 }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">已使用</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats?.total_used || 0 }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-sm">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
                <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总优惠金额</p>
              <p class="text-2xl font-semibold text-gray-900">¥{{ (stats?.total_discount || 0).toLocaleString() }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <div class="bg-white shadow-sm rounded-lg p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
          <!-- 搜索 -->
          <div class="lg:col-span-2">
            <label class="block text-sm font-medium text-gray-700 mb-2">搜索优惠券</label>
            <input
              v-model="filters.search"
              type="text"
              placeholder="优惠券名称或代码..."
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            />
          </div>

          <!-- 类型筛选 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">优惠券类型</label>
            <select
              v-model="filters.type"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            >
              <option value="">全部类型</option>
              <option value="fixed">立减券</option>
              <option value="percent">折扣券</option>
              <option value="shipping">包邮券</option>
              <option value="full_reduction">满减券</option>
            </select>
          </div>

          <!-- 状态筛选 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
            <select
              v-model="filters.is_active"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            >
              <option value="">全部状态</option>
              <option value="1">启用</option>
              <option value="0">禁用</option>
            </select>
          </div>
        </div>
        
        <!-- 筛选按钮 -->
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-600">
            共 {{ coupons.total || 0 }} 个优惠券
          </div>
          <div class="flex gap-2">
            <button
              @click="resetFilters"
              class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
            >
              重置
            </button>
            <button
              @click="applyFilters"
              class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
            >
              应用筛选
            </button>
          </div>
        </div>
      </div>

      <!-- 优惠券列表 -->
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">优惠券</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">使用统计</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">有效期</th>
                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="coupon in coupons.data" :key="coupon.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div>
                    <div class="text-sm font-medium text-gray-900">{{ coupon.name }}</div>
                    <div class="text-sm text-gray-500">{{ coupon.code }}</div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getTypeBadgeClass(coupon.type)">
                    {{ getCouponTypeText(coupon.type) }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  <div class="flex items-center">
                    <div class="text-sm">
                      <div>已发放: {{ coupon.total_distributed || 0 }}</div>
                      <div>已使用: {{ coupon.total_used || 0 }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getStatusBadgeClass(coupon)">
                    {{ getStatusText(coupon) }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  <div v-if="coupon.start_time || coupon.end_time">
                    <div v-if="coupon.start_time">{{ formatDate(coupon.start_time) }}</div>
                    <div v-if="coupon.end_time">{{ formatDate(coupon.end_time) }}</div>
                  </div>
                  <div v-else class="text-gray-400">永久有效</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <div class="flex items-center justify-end space-x-2">
                    <Link :href="route('admin.coupons.edit', coupon.id)" 
                          class="text-gray-600 hover:text-gray-900">
                      编辑
                    </Link>
                    <Link :href="route('admin.coupons.statistics', coupon.id)" 
                          class="text-gray-600 hover:text-gray-900">
                      统计
                    </Link>
                    <Link :href="route('admin.coupons.distribute', coupon.id)" 
                          class="text-gray-600 hover:text-gray-900">
                      发放
                    </Link>
                    <button @click="deleteCoupon(coupon)" 
                            class="text-red-600 hover:text-red-900">
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div v-if="coupons.links" class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
          <div class="flex items-center justify-between">
            <div class="flex-1 flex justify-between sm:hidden">
              <Link v-if="coupons.prev_page_url" :href="coupons.prev_page_url" 
                    class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                上一页
              </Link>
              <Link v-if="coupons.next_page_url" :href="coupons.next_page_url" 
                    class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                下一页
              </Link>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
              <div>
                <p class="text-sm text-gray-700">
                  显示第
                  <span class="font-medium">{{ coupons.from || 0 }}</span>
                  到
                  <span class="font-medium">{{ coupons.to || 0 }}</span>
                  条，共
                  <span class="font-medium">{{ coupons.total || 0 }}</span>
                  条记录
                </p>
              </div>
              <div>
                <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                  <Link v-for="link in coupons.links" :key="link.label" :href="link.url" 
                        :class="[
                          'relative inline-flex items-center px-4 py-2 border text-sm font-medium',
                          link.active 
                            ? 'z-10 bg-orange-50 border-orange-500 text-orange-600' 
                            : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50',
                          link.url === null ? 'opacity-50 cursor-not-allowed' : ''
                        ]"
                        v-html="link.label">
                  </Link>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <ConfirmDialog
      :show="showDeleteDialog"
      :title="'删除优惠券'"
      :message="`确定要删除优惠券 '${deleteCouponData?.code}' 吗？此操作不可撤销。`"
      @confirm="confirmDelete"
      @cancel="showDeleteDialog = false"
    />
  </AdminLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'

const props = defineProps({
  coupons: {
    type: Object,
    required: true
  }
})


const filters = reactive({
  search: '',
  type: '',
  is_active: ''
})

const showDeleteDialog = ref(false)
const deleteCouponData = ref(null)

const getCouponTypeText = (type) => {
  const types = {
    fixed: '立减券',
    percent: '折扣券',
    shipping: '包邮券',
    full_reduction: '满减券'
  }
  return types[type] || type
}

const getTypeBadgeClass = (type) => {
  const classes = {
    fixed: 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800',
    percent: 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800',
    shipping: 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800',
    full_reduction: 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800'
  }
  return classes[type] || 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800'
}

const getStatusText = (coupon) => {
  if (!coupon.is_active) {
    return '已禁用'
  }

  const now = new Date()
  const startsAt = coupon.start_time ? new Date(coupon.start_time) : null
  const expiresAt = coupon.end_time ? new Date(coupon.end_time) : null

  if (startsAt && now < startsAt) {
    return '未开始'
  }

  if (expiresAt && now > expiresAt) {
    return '已过期'
  }

  return '进行中'
}

const getStatusBadgeClass = (coupon) => {
  const status = getStatusText(coupon)
  
  switch (status) {
    case '已禁用':
      return 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800'
    case '未开始':
      return 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800'
    case '已过期':
      return 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800'
    case '进行中':
      return 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800'
    default:
      return 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800'
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const applyFilters = () => {
  router.get(route('admin.coupons.index'), filters, {
    preserveState: true,
    replace: true
  })
}

const resetFilters = () => {
  Object.assign(filters, {
    search: '',
    type: '',
    is_active: ''
  })
  applyFilters()
}

const deleteCoupon = (coupon) => {
  deleteCouponData.value = coupon
  showDeleteDialog.value = true
}

const confirmDelete = () => {
  if (deleteCouponData.value) {
    router.delete(route('admin.coupons.destroy', deleteCouponData.value.id), {
      onSuccess: () => {
        showDeleteDialog.value = false
        deleteCouponData.value = null
      },
      onError: () => {
        showDeleteDialog.value = false
        deleteCouponData.value = null
      }
    })
  }
}
</script>